<!--
  description: transition-group
  @author: GuoSiYue
  date: 2021-11-11
 -->

<template>
    <!-- 列表过渡的移动动画 -->
    <div>
        <button @click="addNum">添加数字</button>
        <button @click="removeNum">删除数字</button>
        <button @click="shuffleNum">打乱数字</button>
        <transition-group name="list" tag="p">
            <span v-for="item in numbers" :key="item" class="item">{{item}}</span>
        </transition-group>
    </div>

    <!-- 列表的交错过渡:通过gsap的延迟delay属性，做一个交替消失的动画 -->
    <div>
        <input v-model="query"/>
        <transition-group name="list"
        tag="ul"
        @beforeEnter="beforeEnter"
        @enter="enter"
        @leave="leave">
            <li v-for="(item, index) in showNames" :key="item" :data-index="index">
                {{item}}
            </li>
        </transition-group>
    </div>
</template>

<script>
    import _ from 'lodash'
    import gsap from 'gsap'
    export default {
        name: "transition-group",
        data() {
            return {
                numbers: [1, 2, 3, 4, 5, 6, 7, 8],
                nextNum: 10,

                query: '',
                names: ["abc", "cba", "nba", "dna", "why", "kobe", "james", "curry"]
            }
        },
        computed: {
          showNames() {
              return this.names.filter(item => {
                  return item.toLowerCase().indexOf(this.query.toLowerCase()) !== -1
              })
          }
        },
        methods: {
            randomIndex() {
                return Math.floor(Math.random() * this.numbers.length)
            },
            addNum() {
                this.numbers.splice(this.randomIndex(), 0, this.nextNum++)
            },
            removeNum() {
                this.numbers.splice(this.randomIndex(), 1)
            },
            shuffleNum() {
                this.numbers = _.shuffle(this.numbers)
            },

            beforeEnter(el) {
                el.style.opacity = 0
                el.style.height = 0
            },
            enter(el, done) {
                gsap.to(el, {
                    opacity: 1,
                    height: '1.6em',
                    delay: el.dataset.index * 0.5,
                    onComplete: done
                })
            },
            leave(el,done) {
                gsap(el, {
                    opacity: 0,
                    height: 0,
                    delay: el.dataset.index * 0.5,
                    onComplete: done
                })
            }
        }
    }
</script>

<style scoped>
    .item {
        display: inline-block;
        margin-right: 10px;
    }
    .list-enter-active,
    .list-leave-active {
        transition: all 1s ease;
    }

    .list-enter-from,
    .list-leave-to {
        opacity: 0;
        transform: translateY(30px)
    }
    .list-move {
        transition: transform 1s ease;
    }
</style>